import Vue from 'vue';
import axios from 'axios';
import md5 from 'js-md5';
import qs from 'qs';
Vue.prototype.$qs = qs;
let base = 'http://39.99.161.1:7007';
// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = base;
var zmitiUtil = {
	baseURL:base,
	getToken:'123',
	TokenSign(){
		let token=this.getToken;
		let timestamp = Number(new Date());
		let sign=md5(token+''+timestamp);
		return '?token='+token+'&timestamp='+timestamp+'&sign='+sign
	},
	Ajax(path, params){
		let loginValue=JSON.parse(window.localStorage.getItem('login'))
		let {token,account,key}=loginValue
		let md5string={
			token:token,
			md5:md5(token+'_'+account+'_'+key).toUpperCase()
		}	
		if(params==undefined){
			params=md5string
		}else{
			params.token=md5string.token
			params.md5=md5string.md5
		}
		let timestamp = Number(new Date())			
		return new Promise((resolve, reject) => {
			axios({
			    method: 'post',
			    url: `${base}/${path}?timestamp=${timestamp}`,
			    headers: {
			      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
			    },
			    data: params
			}).then(res => {
				resolve(res); 
			}).catch((error) => {
				reject(error);
			});
		});
	},
	AjaxExport(path, params){
		let loginValue=JSON.parse(window.localStorage.getItem('login'))
		let {token,account,key}=loginValue
		let md5string={
			token:token,
			md5:md5(token+'_'+account+'_'+key).toUpperCase()
		}	
		if(params==undefined){
			params=md5string
		}else{
			params.token=md5string.token
			params.md5=md5string.md5
		}
		let timestamp = Number(new Date())			
		return new Promise((resolve, reject) => {
			axios({
			    method: 'post',
			    url: `${base}/${path}?timestamp=${timestamp}`,
			    headers: {
			      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
			    },
				data: params,
				 responseType: 'blob'
			}).then(res => {
				resolve(res); 
			}).catch((error) => {
				reject(error);
			});
		});
	},
	localRequest(method,path, params){
		let timestamp = Number(new Date())
		return axios({
		    method: method,
		    url: `${path}?timestamp=${timestamp}`,
		    headers: {
		      "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
		    },
		    data: params
		})
	},
	compareArray(beforeArr,afterArr){
		/**
		 * 方法名：
		 * 功能介绍：返回一个对象里面包含后一个数组比第一个数组增加、减少的数据（适用于去重过后的数组）
		 * 参数：
		 * beforeArr：前一个数组
		 * afterArr：后一个数组
		 */
	    let resObj = {
	        add : [],
	        del : []
	       },
	       cenObj = {};
	   //把beforeArr数组去重放入cenObj 
	    for(let i=0;i<beforeArr.length;i++){
	        cenObj[beforeArr[i]] = beforeArr[i];
	    }
	    //遍历afterArr，查看其元素是否在cenObj中
	    for (let j=0;j<afterArr.length;j++){
	        if (!cenObj[afterArr[j]]){
	            resObj.add.push(afterArr[j]);
	        }else {
	            delete cenObj[afterArr[j]]
	        }
	    }
	    for (let k in cenObj){
	        resObj.del.push(k);
	    }
	    return resObj;
	},
	getBracketStr(text) {//取出字符串花括号里的内容
	    let result = ''
	    let regex = "\\{(.+?)\\}";
	    let arr=text.match(regex);
	    result=arr[1];
	    return result
	},
	formatJson(json, options){
	    var reg = null,
	        formatted = '',
	        pad = 0,
	        PADDING = '    ';
	    options = options || {};
	    options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
	    options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
	    if (typeof json !== 'string') {
	        json = JSON.stringify(json);
	    } else {
	        json = JSON.parse(json);
	        json = JSON.stringify(json);
	    }
	    reg = /([\{\}])/g;
	    json = json.replace(reg, '\r\n$1\r\n');
	    reg = /([\[\]])/g;
	    json = json.replace(reg, '\r\n$1\r\n');
	    reg = /(\,)/g;
	    json = json.replace(reg, '$1\r\n');
	    reg = /(\r\n\r\n)/g;
	    json = json.replace(reg, '\r\n');
	    reg = /\r\n\,/g;
	    json = json.replace(reg, ',');
	    if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
	        reg = /\:\r\n\{/g;
	        json = json.replace(reg, ':{');
	        reg = /\:\r\n\[/g;
	        json = json.replace(reg, ':[');
	    }
	    if (options.spaceAfterColon) {
	        reg = /\:/g;
	        json = json.replace(reg, ':');
	    }
	    (json.split('\r\n')).forEach(function (node, index) {
	            var i = 0,
	                indent = 0,
	                padding = '';
	            if (node.match(/\{$/) || node.match(/\[$/)) {
	                indent = 1;
	            } else if (node.match(/\}/) || node.match(/\]/)) {
	                if (pad !== 0) {
	                    pad -= 1;
	                }
	            } else {
	                indent = 0;
	            }
	            for (i = 0; i < pad; i++) {
	                padding += PADDING;
	            }
	            if(node == "") {
	                formatted += padding + node + '\r\n';
	            }
	            pad += indent;
	        }
	    );
	    return formatted;
	},
    formatDate(time = +new Date(), ms = 1000) {
		var date = new Date(time * ms + 8 * 3600 * 1000); // 增加8小时
		return date.toJSON().substr(0, 10).replace('T', ' ');
	},
	DateCn: function (value) {
        let date = new Date(value);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? ('0' + MM) : MM;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        let h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        let m = date.getMinutes();
        m = m < 10 ? ('0' + m) : m;
        let s = date.getSeconds();
        s = s < 10 ? ('0' + s) : s;
        return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
    },
	DateFormatter(date) {
		let d = new Date(date);
		let year = d.getFullYear(), month = d.getMonth() + 1, day = d.getDate(), hh = d.getHours(), mm = d.getMinutes(), ss = d.getSeconds();
		if (month <= 9) month = '0' + month;
		if (day <= 9) day = '0' + day;
		if (hh <= 9) hh = '0' + hh;
		if (mm <= 9) mm = '0' + mm;
		if (ss <= 9) ss = '0' + ss;
		return year + '-' + month + '-' + day + ' ' + hh + ':' + mm + ':' + ss;
	},
}
// POST
export function post(api, params) {
  return new Promise((resolve, reject) => {
    params = JSON.stringify(params);  
    axios.post(api, params)
      .then((response) => {
        resolve(response);
      }, (err) => {
        reject(err.data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
//GET
export function get(api, data) {
  return new Promise((resolve, reject) => {    
    axios.get(api, { params: data })
      .then((response) => {
        resolve(response);
      }, (err) => {
        reject(err);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
export default zmitiUtil;